﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ESRI.ArcGIS.Server;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.Carto;
using System.Data;
using EAGL.Data;


namespace EAGL.Search
{
    /// <summary>
    /// Spatial searcher has all the functionality of Attribute searcher plus the ability to 
    /// search spatially.
    /// </summary>
    public class SpatialSearcher: AttributeSearcher
    {
        #region =========================== PRIVATE ===============================

        protected IGeometry geometry;
        protected esriSpatialRelEnum spatialRelation; 
       

        #endregion

        #region =========================== PUBLIC ================================

        public IGeometry Geometry
        {
            get { return this.geometry; }
            set { this.geometry = value; }
        }

        public esriSpatialRelEnum SpatialRelation
        {
            get { return this.spatialRelation; }
            set { this.spatialRelation = value; }
        }

        public override DataTable Search()
        {
            ISpatialFilter sf;
            if (serverMode)
            {
                sf = this.serverContext.CreateObject("esriGeoDatabase.SpatialFilter") as ISpatialFilter;
            }
            else
            {
                sf = new SpatialFilterClass();
            }

            sf.WhereClause = this.WhereClause;
            sf.SubFields = this.fieldsClause;
            sf.Geometry = this.geometry;
            sf.SpatialRel = this.spatialRelation;
            

            IFeatureCursor cur = this.featureClass.Search(sf, false);

            List<IField> fields;

            fields = this.createFields(cur);

            DataTableBuilder builder = new DataTableBuilder(fields);

            DataTable table = new DataTable();
            table = builder.DataTable;

            // Fill the table
            DataTableAdapter adapter = new DataTableAdapter((ICursor)cur);
            adapter.Fill(table);
            return table;

        }

        
        
        #endregion

    }
}
